package com.ultrasoft.farmasoft.web;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ultrasoft.farmasoft.domain.Access;
import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Product;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Providerpharmacy;
import com.ultrasoft.farmasoft.domain.Rol;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.domain.Userprovider;
import com.ultrasoft.farmasoft.domain.UserproviderPK;
import com.ultrasoft.farmasoft.service.GeneralAdministrationService;
import com.ultrasoft.farmasoft.service.ProviderService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
import com.ultrasoft.farmasoft.util.UtilUseFulTree;
import com.ultrasoft.farmasoft.validator.AccessValidator;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="/Provider")
public class ProviderController implements ServletContextAware {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	private String providerId_ 		= "_providerId";
	private String userProviderId_ 	= "_userProviderId";
	
	private final ProviderService providerService;
	private final GeneralAdministrationService generalAdminService;
	
	private ServletContext servletContext;

	
	@Autowired
    public ProviderController(ProviderService providerService, GeneralAdministrationService generalAdminService) {
        this.providerService = providerService;
        this.generalAdminService = generalAdminService;
    }
	
	/************************************************************************************************************************************************/
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	//  E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\farmasoft\resources\image\estido.jpg revisar 
	private void saveImage(String filename, MultipartFile image,HttpServletRequest request)throws RuntimeException, IOException {
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			System.out.println(basePath);
			
			File file = new File(servletContext.getRealPath("/")+"/resources/image/"+filename);
			FileUtils.writeByteArrayToFile(file, image.getBytes());
			System.out.println("Localizacion del Archivo almacenado:  " + file.toString());
		} catch (IOException e) {
			throw e;
		}
	}
	private void validateImage(MultipartFile image) {
		if (!(image.getContentType().equals("image/jpeg")||  
				image.getContentType().equals("image/png")||image.getContentType().equals("image/gif"))) {
			throw new RuntimeException("Solo Imagenes JPG, PNG, GIF son Aceptados");
		}
	}
	/************************************************************************************************************************************************/

	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	
    @RequestMapping(value="/mainProv",method = RequestMethod.GET)
    protected String handleIndex(HttpServletRequest request, Model model) throws ServletException {
    	if(this.sessionControl(request)){
        	return UtilCommon.fMainProvider+"mainProv";
    	}else{
    		return "redirect:/mainFront";
    	}	
    }
    
    @RequestMapping(value="/ManagerProv/providers",method = RequestMethod.GET)
    protected String handleListProviders(HttpServletRequest request, Model model) throws ServletException {
    	if(this.sessionControl(request)){
//    		model.addAttribute("listProviders",providerService.getlistProviders());
//    		model.addAttribute("listProvidersDischarged",providerService.getlistProvidersDischarged());
    		model.addAttribute("listProviders",providerService.getListProvider(s_pharmacyId, true));
    		model.addAttribute("listProvidersDischarged",providerService.getListProvider(s_pharmacyId, false));
        	return UtilCommon.fproviders+"providers";
    	}else{
    		return "redirect:/mainFront";
    	}
    }
    @RequestMapping(value = "/ManagerProv/ajaxGiveLowOrHighToProvider", method = RequestMethod.GET)
	public @ResponseBody String handleRequestAjaxGiveLowOrHighToProvider(@RequestParam Integer providerId,@RequestParam boolean active){
		Provider provider = providerService.searchProviderByProviderId(providerId);
		provider.setActive(active);
		providerService.updateProvider(provider);
        String lowHigh = "";
        if(active)
        	lowHigh = " Se dio de Alta a ";
        else
        	lowHigh = " Se dio de Baja a ";
        return lowHigh;
    }
    
    
    
    
    
    
    
    /*
    @RequestMapping(value="/ManagerProv/new",method = RequestMethod.GET)
    protected String newProvider(HttpServletRequest request, Model model) throws ServletException{
    	if(this.sessionControl(request)){
    		model.addAttribute("provider",new Provider());
    		model.addAttribute("countries", generalAdminService.getCountryList());
    		model.addAttribute("parts", generalAdminService.getRegionList());
    		model.addAttribute("towns", generalAdminService.getLocality());
        	return UtilCommon.fproviders+"formProvider";
    	}else{
    		return "redirect:/mainFront";
    	}
    }    
    @RequestMapping(value="/ManagerProv/new",method = RequestMethod.POST)
    protected String processForm(HttpServletRequest request, Model model, @RequestParam String action) throws ServletException{
    	if(this.sessionControl(request)){
    		Provider provider = new Provider();
    		System.out.println("entro aqui!!!");
    		//providerService.addProvider(provider);
        	return "redirect:/Provider/ManagerProv/providers?_menuId=2&_subMenuId=4&_optionId=1";
    	}else{
    		return "redirect:/mainFront";
    	}
    }

    */
    
    
    
    
    
    
    
    
    
    
    
    private String redirectProvider(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/Provider/mainProv?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}	
	private String handleRedirectProvider(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
    				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
    				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		} catch (Exception e) {
			return redirectProvider(request);
		}
    }
    
    @RequestMapping(value="/ManagerVisit/visitors",method = RequestMethod.GET)
    protected String handleManagerVisitVisitors(HttpServletRequest request, Model model) throws ServletException {
    	if(this.sessionControl(request)){
    		int tempProviderId=UtilConverter.converterStringToInteger(request,providerId_);
    		if(tempProviderId != -1){
    			model.addAttribute("listUserProviderActive",providerService.getListUserProviderByproviderId(tempProviderId,true));
    			model.addAttribute("listUserProviderInactive",providerService.getListUserProviderByproviderId(tempProviderId,false));   
    			model.addAttribute("listRolProvider",providerService.getListRolProvider());
    		}
    		model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
    		return UtilCommon.fvisitors+"visitors";	
    	}
    	return redirectProvider(request);
    }
    @RequestMapping(value="/ManagerVisit/visitorsNew", method=RequestMethod.GET)
	public String handleRequestManagerVisitVisitorsNew(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	// name of mapping with the same name of the database			
			model.addAttribute("listRolProvider",providerService.getListRolProvider());
			model.addAttribute("userProvider",new Userprovider());
			return UtilCommon.fvisitors+"formVisitors";
		}else
			return redirectProvider(request);
	}
    @RequestMapping(value="/ManagerVisit/visitorsNew" , method = RequestMethod.POST)
    public String onSubmitRequestManagerVisitVisitorsNew(@Valid Userprovider userProvider,BindingResult result,Model model,@RequestParam String action,@RequestParam(value = "image", required = false) List<MultipartFile> image,HttpServletRequest request){
    	if(result.hasErrors()){
			System.out.println("reload with by error");		
			model.addAttribute("listRolProvider",providerService.getListRolProvider());
			model.addAttribute("userProvider",new Userprovider());
			return UtilCommon.fvisitors+"formVisitors";
		}
    	
    	if( !action.equals("Cancelar")){ 
    		String picture="";
    		if (!image.get(0).isEmpty()) {
				try {
					for (MultipartFile multipartFile : image) {
						validateImage(multipartFile);
						picture="resources/image/"+multipartFile.getOriginalFilename();
					}
				} catch (RuntimeException re) {}
			}
    		
			int providerId 		=  userProvider.getProvider().getProviderId();			
			if(providerId != -1 ){
				int userProviderId = providerService.searchUserProviderIdByuserProviderIdMax();
				userProvider.setRolProviderId(providerService.searchRolProviderByRolProviderId(userProvider.getRolProviderId().getRolProviderId()));
				userProvider.setUserproviderPK(new UserproviderPK(providerId,(userProviderId+1)));
				userProvider.setActive(true);
				userProvider.setBirthdate(UtilConverter.converterStringToDate(request,"birthdate"));
				if(!image.get(0).isEmpty())
					userProvider.setPicture(picture);
				providerService.addUserProvider(userProvider);
				try {
	    			for (MultipartFile multipartFile : image) {
	        			saveImage(multipartFile.getOriginalFilename(), multipartFile,request);
					}
	    		} catch (IOException e) {
	    			System.out.println("no se subio Archivo");
	    		}
				return handleRedirectProvider(request,"Provider/ManagerVisit/visitors?")+"&"+providerId_+"="+providerId;				
			}
		}
		return handleRedirectProvider(request,"Provider/ManagerVisit/visitors?")+"&"+providerId_+"="+UtilConverter.converterStringToInteger(request,providerId_);
    }
    @RequestMapping(value="/ManagerVisit/visitorsEdit", method=RequestMethod.GET)
	public String handleRequestManagerVisitVisitorsEdit(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	// name of mapping with the same name of the database			
			model.addAttribute("listRolProvider",providerService.getListRolProvider());
			Userprovider userProvider = providerService.searchUserProviderByUserProviderIdByProviderId(UtilConverter.converterStringToInteger(request,userProviderId_), UtilConverter.converterStringToInteger(request,providerId_));
			if(userProvider == null)
				return handleRedirectProvider(request,"Provider/ManagerVisit/visitors?")+"&"+providerId_+"="+UtilConverter.converterStringToInteger(request,providerId_);
			model.addAttribute("userProvider",userProvider);
			return UtilCommon.fvisitors+"formVisitors";
		}else
			return redirectProvider(request);
	}
    @RequestMapping(value="/ManagerVisit/visitorsEdit" , method = RequestMethod.POST)
    public String onSubmitRequestManagerVisitVisitorsEdit(@Valid Userprovider userProvider,Model model,@RequestParam String action,@RequestParam(value = "image", required = false) List<MultipartFile> image,HttpServletRequest request){
		if( !action.equals("Cancelar")){ 
			String picture="";
    		if (!image.get(0).isEmpty()) {
				try {
					for (MultipartFile multipartFile : image) {
						validateImage(multipartFile);
						picture="resources/image/"+multipartFile.getOriginalFilename();
					}
				} catch (RuntimeException re) {}
			}
			
			Userprovider temp = providerService.searchUserProviderByUserProviderIdByProviderId(UtilConverter.converterStringToInteger(request,userProviderId_), UtilConverter.converterStringToInteger(request,providerId_));
			temp.setName(userProvider.getName());
			temp.setLastName(userProvider.getLastName());
			temp.setLastName2(userProvider.getLastName2());
			temp.setCi(userProvider.getCi());
			temp.setGenero(userProvider.getGenero());
			temp.setCellphone(userProvider.getCellphone());
			temp.setPhone(userProvider.getPhone());
			temp.setEmail(userProvider.getEmail());
			temp.setEmail2(userProvider.getEmail2());
			temp.setAddress(userProvider.getAddress());
			temp.setBirthdate(UtilConverter.converterStringToDate(request,"birthdate"));
			if(!image.get(0).isEmpty())
				temp.setPicture(picture);
			
			try {
    			for (MultipartFile multipartFile : image) {
        			saveImage(multipartFile.getOriginalFilename(), multipartFile,request);
				}
    		} catch (IOException e) {
    			System.out.println("no se subio Archivo");
    		}
			providerService.updateUserProvider(temp);
		}
		return handleRedirectProvider(request,"Provider/ManagerVisit/visitors?")+"&"+providerId_+"="+UtilConverter.converterStringToInteger(request,providerId_);
    }
    @RequestMapping(value = "/ManagerVisit/ajaxGiveLowOrHighToVisitors", method = RequestMethod.GET)
	public @ResponseBody String handleRequestajAxGiveLowOrHighToVisitors(@RequestParam Integer providerId,@RequestParam Integer userProviderId,@RequestParam boolean active){
    	Userprovider temp = providerService.searchUserProviderByUserProviderIdByProviderId(userProviderId,providerId);
    	if(temp == null)
    		return "vacio el objeto";
    	temp.setActive(active);
    	providerService.updateUserProvider(temp);
        String lowHigh = "";
        if(active)
        	lowHigh = " Se dio de Alta a ";
        else
        	lowHigh = " Se dio de Baja a ";
        return lowHigh;
    }
    
    /*Remove visitors*/
    @RequestMapping(value = "/ManagerVisit/removeVisitor", method = RequestMethod.GET)
    public @ResponseBody String handleProviderRemoveUserProvider( @RequestParam Integer userProviderId, @RequestParam Integer providerId,@RequestParam String name, HttpServletRequest request){
    	//System.out.println(request.getParameterMap()); /*for see parameters removeVisitor*/
  		providerService.removeUserProvider(providerService.searchUserProviderByUserProviderIdByProviderId(userProviderId, providerId));
  		return "El visitador "+name+" se Elimino correctamente!!!";
    }
  	
}
